package com.menker.app.ui.splash;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Looper;
import android.os.MessageQueue;
import android.text.TextUtils;
import android.view.Gravity;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.menker.app.Constants;
import com.menker.app.MyApp;
import com.menker.app.R;
import com.menker.app.biz.CurrentUser;
import com.menker.app.common.SharedPreferencesHelper;
import com.menker.app.common.Utils;
import com.menker.app.di.DaggerScope;
import com.menker.app.di.Injector;
import com.menker.app.rest.ApiHelper;
import com.menker.app.rest.result.AppInfo;
import com.menker.app.util.DialogUtils;
import com.menker.app.util.IntentUtils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.res.StringRes;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import myandroid.library.util.ApplicationHelper;
import rx.Subscriber;

/**
 * @author J.Huang
 * @version 1.0
 * @since 17/6/24
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(SplashActivity.class)
@Fullscreen
@EActivity(R.layout.activity_splash)
public class SplashActivity extends Activity {

    @Inject
    SharedPreferencesHelper mSharedPreferencesHelper;
    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;

    @StringRes(R.string.error_no_internet)
    String strNoInternet;
    @StringRes(R.string.error_api)
    String strErrorApi;

    private Subscriber<AppInfo> mAppInfoSubscriber;

    private static final int APP_PERMISSION = 100;

    private boolean permissionTip = true;

    NormalDialog mPermissionDialog;

    public void onResume() {
        super.onResume();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    ) {
                if (permissionTip) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                    }, APP_PERMISSION);
                }
            } else {
                Injector.initSplashActivityComponent().inject(this);
                getAppInfo();
            }
        } else {
            Injector.initSplashActivityComponent().inject(this);
            getAppInfo();
        }
    }

    @Override
    protected void onDestroy() {
        if (mAppInfoSubscriber != null) {
            mAppInfoSubscriber.unsubscribe();
            mAppInfoSubscriber = null;
        }

        if (mPermissionDialog != null) {
            mPermissionDialog.superDismiss();
            mPermissionDialog = null;
        }

        DialogUtils.dismissAllDialog();

        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);

        permissionTip = false;

        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {

                return false;
            }
        });

        switch(requestCode)
        {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(!granted) {
                    // 没有获取到权限，做特殊处理
                    mPermissionDialog = new NormalDialog(this);

                    mPermissionDialog.isTitleShow(false)
                            .btnNum(1)
                            .bgColor(Color.parseColor("#FFFFFF"))
                            .cornerRadius(5)
                            .content("应用需要\"电话状态\"权限才能正常使用\n请在\"设置\"中开启权限")
                            .contentGravity(Gravity.CENTER)
                            .contentTextSize(13)
                            .contentTextColor(Color.parseColor("#333333"))
                            .dividerColor(Color.parseColor("#CCCCCC"))
                            .btnText("确定")
                            .btnTextSize(15.5f)
                            .btnTextColor(Color.parseColor("#0092FF"))
                            .widthScale(0.7f)
                            .show();

                    mPermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mPermissionDialog.dismiss();
                            finish();
                            ApplicationHelper.getInstance().exit();
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {}

    @Background(delay = 3000)
    void delayToFinishApp() {
        finish();
        ApplicationHelper.getInstance().exit();
    }

    @Background(delay = 2000)
    void delayToNextPage() {
        String ticket = mSharedPreferencesHelper.getString(Constants.API.KEY_TICKET, "");
        if (TextUtils.isEmpty(ticket) || ticket.length() < 20) {
            IntentUtils.toLogin(SplashActivity.this);
        } else {
            IntentUtils.toMainActivity(SplashActivity.this);
        }

        finish();
    }

    void getAppInfo() {
        if (!Utils.Network.isNetworkAvailable()) {
            DialogUtils.showNoInternetDialog(this);
            return;
        }

        delayToNextPage();
    }

}
